package com.wh.webflux.handler;

import com.wh.webflux.event.DelayDeleteEventListener;
import com.wh.webflux.pojo.Delay;
import com.wh.webflux.pojo.DelayDeleteSuccessEvent;
import com.wh.webflux.repository.DelayRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

import java.time.LocalDateTime;

import static org.springframework.web.reactive.function.server.ServerResponse.ok;

/**
 * @description:
 * @author: GooGoo
 * @time: 2023/4/10 12:10
 */
@Component
public class DelayHandler {
    @Autowired
    DelayRepository delayRepo;

    @Autowired
    private ApplicationContext applicationContext;

    public Mono<ServerResponse> getAllDelays(ServerRequest request) {
        return ok().contentType(MediaType.APPLICATION_JSON).body(delayRepo.findAll(), Delay.class);
    }

    public Mono<ServerResponse> addDelay(ServerRequest request) {
        return ok().contentType(MediaType.APPLICATION_JSON).body(delayRepo.saveAll(request.bodyToFlux(Delay.class)), Delay.class);
    }

    public Mono<ServerResponse> deleteDelays(ServerRequest request) {

        long id = Long.parseLong(request.pathVariable("id"));
        return delayRepo.findById(id).flatMap(delay -> {
            Mono<Void> delete = delayRepo.delete(delay);
            applicationContext.publishEvent(new DelayDeleteSuccessEvent(id));
            return delete.then(ok().build());
        }).switchIfEmpty(ok().build());
    }

}
